/**
 * Notes: 资讯后台管理
 * Ver : CCMiniCloud Framework 2.0.1 ALL RIGHTS RESERVED BY cclinux0730 (wechat)
 * Date: 2021-07-11 07:48:00 
 */

const BaseProjectAdminService = require('./base_project_admin_service.js'); 
const dataUtil = require('../../../../framework/utils/data_util.js');
const util = require('../../../../framework/utils/util.js'); 
const cloudUtil = require('../../../../framework/cloud/cloud_util.js');

const NewsModel = require('../../model/news_model.js');
const UserModel = require('../../model/user_model.js');

class AdminNewsService extends BaseProjectAdminService {


	/**添加资讯 */
	async insertNews(
		userId, {cateId,cateName,desc,forms,order,title}
	) {


		try {
	   
			let userName = await UserModel.getOneField({ USER_MINI_OPENID: userId }, 'USER_NAME');
			const data = {
				_pid: this.getProjectId(),
				//NEWS_ID: uniCloud.util.uniqueId(),
				NEWS_TITLE: title,
	            NEWS_DESC: desc,
				NEWS_STATUS: 1, // 默认状态为待处理
				NEWS_CATE_ID: cateId, // 分类ID，根据实际情况设置
				NEWS_CATE_NAME: cateName, // 分类名称，根据实际情况设置
				NEWS_ORDER: order,
				NEWS_VOUCH: 0,
				NEWS_CONTENT:[],
				NEWS_QR:'',
				NEWS_VIEW_CNT:0,
				NEWS_PIC:[],
				NEWS_FORMS:forms,
				NEWS_OBJ:dataUtil.dbForms2Obj(forms),

				NEWS_ADD_TIME: Date.now(),
				NEWS_EDIT_TIME: Date.now(),
				NEWS_ADD_IP: '', // IP 地址，可以从客户端获取
				NEWS_EDIT_IP: '' // IP 地址，可以从客户端获取
			};
	  
			// 插入数据
			let id = await NewsModel.insert(data);
	  
			// 返回成功信息或数据
			return await NewsModel.getOne(id);
		} catch (error) {
			console.error('[插入时发生错误]', error);
			throw new Error('插入时出现问题，请稍后再试或联系支持人员');
		}

	}

	/**删除资讯数据 */
	async delNews(id) {
		await NewsModel.del({ _id: id });
		return true;

	}

	/**获取资讯信息 */
	async getNewsDetail(id) {
		let fields = '*';

		let where = {
			_id: id
		}
		let news = await NewsModel.getOne(where, fields);
		if (!news) return null;

		return news;
	}

	// 更新forms信息
	async updateNewsForms({
		id,
		hasImageForms
	}) {
		throw new Error('[跑腿]该功能暂不开放，如有需要请加作者微信：15072363681');

	}


	/**
	 * 更新富文本详细的内容及图片信息
	 * @returns 返回 urls数组 [url1, url2, url3, ...]
	 */
	async updateNewsContent({
		id,
		content // 富文本数组
	}) {
		const updates = {
			NEWS_CONTENT: content
	 };
 
		 // 执行更新操作
		await NewsModel.insertOrUpdate({ _id: id },  updates
 );
		 return await NewsModel.getOne(id);
	}

	/**
	 * 更新资讯图片信息
	 * @returns 返回 urls数组 [url1, url2, url3, ...]
	 */
	async updateNewsPic({id,imgList}) {
		const updates = {
			NEWS_PIC: imgList
	 };
 
		 // 执行更新操作
		await NewsModel.insertOrUpdate({ _id: id },  updates
 );
		 return await NewsModel.getOne(id);
	}


	/**更新资讯数据 */
	async editNews(
		userId, {id,cateId,cateName,desc,forms,order,title}
	) {
		try {
			//this.checkMy(id,userId)
				  // 构造更新数据
			 const updates = {
					 NEWS_TITLE: title,
					 NEWS_DESC: desc,
					 NEWS_CATE_ID: cateId,
					 NEWS_CATE_NAME: cateName,
					 NEWS_ORDER: order,
					 NEWS_FORMS: forms,
					 NEWS_OBJ: dataUtil.dbForms2Obj(forms),
					 NEWS_EDIT_TIME: Date.now(),
					 NEWS_EDIT_IP: '' // IP 地址，可以从客户端获取
			  };
		  
				  // 执行更新操作
				  await NewsModel.insertOrUpdate({ _id: id },  updates
		  );
		  
				  // 返回更新后的邮件信息
				  return await NewsModel.getOne(id);
			  } catch (error) {
				  console.error('[编辑时发生错误]', error);
				  throw new Error('编辑时出现问题，请稍后再试或联系支持人员');
			  }
			
			}

	/**取得资讯分页列表 */
	async getAdminNewsList({
		search, // 搜索条件
		sortType, // 搜索菜单
		sortVal, // 搜索菜单
		orderBy, // 排序
		whereEx, //附加查询条件
		page,
		size,
		isTotal = true,
		oldTotal
	}) {

		orderBy = orderBy || {
			'NEWS_ORDER': 'asc',
			'NEWS_ADD_TIME': 'desc'
		};
		let fields = 'NEWS_TITLE,NEWS_DESC,NEWS_CATE_ID,NEWS_CATE_NAME,NEWS_EDIT_TIME,NEWS_ADD_TIME,NEWS_ORDER,NEWS_STATUS,NEWS_CATE2_NAME,NEWS_VOUCH,NEWS_QR,NEWS_OBJ';

		let where = {};
		where.and = {
			_pid: this.getProjectId() //复杂的查询在此处标注PID
		};

		if (util.isDefined(search) && search) {
			where.or = [
				{ NEWS_TITLE: ['like', search] },
			];

		} else if (sortType && util.isDefined(sortVal)) {
			// 搜索菜单
			switch (sortType) {
				case 'cateId': {
					where.and.NEWS_CATE_ID = String(sortVal);
					break;
				}
				case 'status': {
					where.and.NEWS_STATUS = Number(sortVal);
					break;
				}
				case 'top': {
					where.and.NEWS_ORDER = 0;
					break;
				}
				case 'sort': {
					orderBy = this.fmtOrderBySort(sortVal, 'NEWS_ADD_TIME');
					break;
				}

			}
		}

		return await NewsModel.getList(where, fields, orderBy, page, size, isTotal, oldTotal);
	}

	/**修改资讯状态 */
	async statusNews(id, status) {
    const updates = {
			NEWS_STATUS: status
	 };
 
		 // 执行更新操作
		return await NewsModel.insertOrUpdate({ _id: id },  updates)
	}

	/**置顶与排序设定 */
	async sortNews(id, sort) {
    const updates = {
			NEWS_ORDER: sort
	 };
 
		 // 执行更新操作
		return await NewsModel.insertOrUpdate({ _id: id },  updates)
	}
}

module.exports = AdminNewsService;